package oh.how.easy.fck.util;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.tapestry5.TapestryFilter;
import org.apache.tapestry5.ioc.Registry;

/**
 * Utilities to get T5 Registry from request.
 * @author Ville Virtanen
 */
public class LegacyT5ServiceHelper {

    public static final String TAPESTRY_REGISTRY_REQUEST_KEY = LegacyT5ServiceHelper.class.getName();

    /**
     * Returns the requested service proxy, or null if no such service exists.<br />
     * The Registry must be set using the method setRegistryToRequest prior to using this method.
     * @param clazz
     * @param httpServletRequest
     * @return
     */
    public static <T> T getService(Class<T> clazz, HttpServletRequest httpServletRequest) {
        Registry registry = (Registry)httpServletRequest.getAttribute(TAPESTRY_REGISTRY_REQUEST_KEY);
        try {
            return registry.getService(clazz);
        } catch (RuntimeException exception) { //Not an exception, just that dev hasn't specified service to do some task -> use defaults.
            return null;
        }
    }

    /**
     * Returns the requested service proxy, or null if no such service exists.
     * @param clazz
     * @param servletContext
     * @return
     */
    public static <T> T getService(Class<T> clazz, ServletContext servletContext) {
        Registry registry = (Registry)servletContext.getAttribute(TapestryFilter.REGISTRY_CONTEXT_NAME);
        try {
            return registry.getService(clazz);
        } catch (RuntimeException exception) { //Not an exception, just that dev hasn't specified service to do some task -> use defaults.
            return null;
        }
    }

    /**
     * Sets the Tapestry 5 Registry to given request, so that services may be fetched and used if reference to request can be obtained later.
     * @param servletContext
     * @param httpServletRequest
     */
    public static void setRegistryToRequest(ServletContext servletContext, HttpServletRequest httpServletRequest) {
        httpServletRequest.setAttribute(TAPESTRY_REGISTRY_REQUEST_KEY, servletContext.getAttribute(TapestryFilter.REGISTRY_CONTEXT_NAME));
    }

}